# -*- coding: utf-8 -*-

import os
import sys
import serial
import threading
from time import sleep

class Uart(object):
        def __init__(self , parent , port ,baud ):
            self.err = 0 
            self.port_open = False 
            self.parent = parent
            self.port_num = port 
            self.baud_rate = baud
            self.serial = serial.Serial()
            
        def open_port_opr(self):
            try:
                print("port:" + str(self.port_num) + "baud:" + str(self.baud_rate))
                #self.serial = serial.Serial( self.port_num , self.baud_rate)
                self.serial.port = self.port_num
                self.serial.baudrate = self.baud_rate
                self.serial.open()
                self.port_open = True 
                print("i open success")
                #启用接收线程
                self.start_recv_thread()
            except: 
                self.err = -1 
                self.port_open = False
                print("i open faild") 

           
        #接受数据方法
        def uart_recv_thread(self):
            print("start uart_recv_thread")
            #while(True):
            while(self.port_open):
                try:
                    #sleep(1)
                    #print(self.serial.read())
                    #data = self.serial.read()
                    data = self.serial.read_all().decode()
                    #print(self.serial.readall())
                    #recv_data_raw = self.serial.read_all()
                    #data = "-->" + recv_data_raw
                    #print("rcv data is " + data.decode('utf-8'))
                    #data = "test"
                    if (data != ""):
                        data = "rcv data is -->" + data + "\n"
                        print("rcv data is " + data)
                        self.parent.data_rcv_back_call(data)
                     
                    #print(data)
                except:
                    print("receive data err")
                    break

        #接收数据线程
        def start_recv_thread(self):
            thread=threading.Thread(target=self.uart_recv_thread,daemon=True)
            thread.start()

        #发送数据
        def send_uart_data( self , data):
            print("i try to send a data: " + data)
            self.serial.write(data.encode())

        #关闭串口
        def uart_close(self):
            print("try close")
            self.serial.close()
            self.port_open = False

